#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import datetime
import math

import geobox
import logging

from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

import googledatabase
import getcounter
#import commonfunction

#增加一个计数，若要减少，那么传负值
def AddOnePropertyCount(ItemKey, PropertyName, AddValue):
    Item = db.get(ItemKey)
    if Item:
        setattr(Item, PropertyName, getattr(Item, PropertyName) + AddValue)
        Item.put()



#分页、按ID反向 获得一个表的内容    
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneTableRecordAtPage(TableName, PageSize, TagID = '', Where = ''):
    if 1 > len(TableName):
        return None
    
    #只有最新的、第一页才放入缓存
    CatchRecordName = TableName + '_New'
    CatchPrePageName = TableName + '_PrePage'
    CatchNextPageName = TableName + '_NextPage'
    if 1 > len(TagID):
        CatchRecord = memcache.get(CatchRecordName)
        if CatchRecord != None:
#            logging.debug("--------------------- CatchRecord != None")
            return CatchRecord, memcache.get(CatchPrePageName), memcache.get(CatchNextPageName)

    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagID):
        Query = db.GqlQuery( 'SELECT * FROM %s WHERE ID > :1 ORDER BY ID' % (TableName), TagID )
        if 0 < len(Where):
            Query = db.GqlQuery( 'SELECT * FROM %s WHERE %s AND ID > :1 ORDER BY ID' % (TableName, Where), TagID )
            
        Results = Query.fetch(PageSize)
        if Results:
            PrePageTag = str(Results[len(Results) - 1].ID)


    #计算下一页起始ID
    Query = db.GqlQuery( 'SELECT * FROM %s ORDER BY ID DESC' % (TableName) )
    if 0 < len(Where):
        Query = db.GqlQuery( 'SELECT * FROM %s WHERE %s ORDER BY ID DESC' % (TableName, Where) )
        
    if 0 < len(TagID):
        Query = db.GqlQuery( 'SELECT * FROM %s WHERE ID <= :1 ORDER BY ID DESC' % (TableName), TagID )
        if 0 < len(Where):
            Query = db.GqlQuery( 'SELECT * FROM %s WHERE %s AND ID <= :1 ORDER BY ID DESC' % (TableName, Where), TagID )
        
    Results = Query.fetch(PageSize + 1)
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].ID)
        Results = Results[:PageSize]

    #只有最新的、第一页才放入缓存
    if 1 > len(TagID) and Results:
        memcache.set(CatchRecordName, Results)
        memcache.set(CatchPrePageName, PrePageTag)
        memcache.set(CatchNextPageName, NextPageTag)

    #logging.debug("--------------------- len(Results) = %d, Results = %s, PrePageTag = %s, NextPageTag = %s", len(Results), Results, PrePageTag, NextPageTag)
    return Results, PrePageTag, NextPageTag





#分页、逆时获得某用户某个表的记录集（函数内转换了朋友的昵称）
#返回： 结果集, 前一页起始TagDate, 后一页起始TagDate
def GetOneUserTableRecordFromDate(TableName, LoginID, PageSize, TimeDelta, TagDate = '', ModifyNickNameFieldList = []):
#    logging.debug( "-------------- GetOneUserTableRecordFromDate 1: TableName = %s, LoginName = %s, TimeDelta = %s, TagDate = %s, ModifyNickName = %d"
#                   % (TableName, LoginName, TimeDelta, TagDate, ModifyNickName) )
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM %s WHERE LoginID = :1 AND Date > :2 ORDER BY Date' % (TableName),
                             LoginID, commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- GetOneUserTableRecordFromDate 2: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( 'SELECT * FROM %s WHERE LoginID = :1 ORDER BY Date DESC' % (TableName), LoginID )
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM %s WHERE LoginID = :1 AND Date <= :2 ORDER BY Date DESC' % (TableName),
                             LoginID, commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- GetOneUserTableRecordFromDate 3: len(Results) = %d" % (len(Results)) )
    
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间
    for Item in Results:
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag




#获得某个表的一条记录
def GetOneTableItem(TableName, ItemKeyStr):
    if 1 > len(TableName) or 1 > len(ItemKeyStr):
        return None

#    logging.debug("------------ GetOneTableItem: TableName = %s, ItemKeyStr = %s" % (TableName, ItemKeyStr))
    Query = db.GqlQuery( 'SELECT * FROM %s WHERE __key__ = :1' % (TableName), db.Key(ItemKeyStr) )
    Results = Query.fetch(1)
    if Results:
        return Results[0]
    else:
        return None


#判断一个项目是否在缓存记录集中
def TheItemInMemcacheRecord(CatchRecordName, ItemKeyStr):
    CatchRecord = memcache.get(CatchRecordName)
    if CatchRecord:
        for Item in CatchRecord:
            if str(Item.key()) == ItemKeyStr:
                return True

    return False


#获得一个表的倒数第N的记录
def GetReciprocalItem(TableName, ReciprocalNumber, ColName = 'Date'):
    Query = db.GqlQuery( 'SELECT * FROM %s ORDER BY %s DESC' % (TableName, ColName) )
    Results = Query.fetch(ReciprocalNumber)
    if Results:
        Index = ReciprocalNumber - 1
        if len(Results) - 1 < Index:
            Index = len(Results) - 1

        return Results[Index]

    return None

